package com.smartinput.user.application.service

import com.mensanyun.kotool.exception.BaseException
import com.mensanyun.kotool.util.UlidUtil
import com.smartinput.auth.application.dto.*
import com.smartinput.user.application.dto.*
import com.smartinput.user.domain.model.User
import com.smartinput.user.domain.repository.UserRepository
import com.smartinput.user.query.service.UserQueryService
import com.smartinput.security.JwtService
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import java.time.LocalDateTime

@Service
class UserService(
    private val userRepository: UserRepository,
    private val userQueryService: UserQueryService,
    private val passwordEncoder: PasswordEncoder,
    private val jwtService: JwtService
) {

    fun register(userName: String, password: String): RegisterResponse {
        // 检查用户名是否已存在
        if (userRepository.existsByUserName(userName)) {
            throw BaseException("用户名已存在")
        }

        // 创建新用户
        val user = User(
            uid = UlidUtil.generate(),
            userName = userName,
            password = passwordEncoder.encode(password),
            enabled = true,
            createdAt = LocalDateTime.now()
        )

        val savedUser = userRepository.save(user)
        
        // 生成JWT token
        val token = jwtService.generateToken(savedUser.uid, savedUser.userName)
        
        return RegisterResponse(
            userId = savedUser.uid,
            userName = savedUser.userName,
            token = token
        )
    }

    fun login(userName: String, password: String): LoginResponse {
        val user = userRepository.findByUserName(userName)
            ?: throw BaseException("用户名或密码错误")

        if (!passwordEncoder.matches(password, user.password)) {
            throw BaseException("用户名或密码错误")
        }

        if (!user.enabled) {
            throw BaseException("账户已被禁用")
        }

        // 生成JWT token
        val token = jwtService.generateToken(user.uid, user.userName)
        
        return LoginResponse(
            userId = user.uid,
            userName = user.userName,
            token = token
        )
    }

    fun getCurrentUserProfile(): UserProfile {
        val authentication = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication
        val userId = authentication.name
        
        val user = userQueryService.findById(userId) ?: throw BaseException("用户不存在")
        
        return UserProfile(
            userId = user.uid,
            userName = user.userName,
            createdAt = user.createdAt.toString()
        )
    }
} 